﻿CREATE PROCEDURE [acms].[Post_Put]
	@Id int, 
	@SiteId int, 
	@ParentId int, 
	@Name varchar(100), 
	@DisplayName varchar(100), 
	@TemplateId int, 
	@ThumbnailId int,
	@Summary varchar(2000), 
	@Sequence int, 
	@Tags varchar(2000),
	@VersionId timestamp,
	@IdOut int output, 
	@SiteNameOut varchar(50) output, 
	@ParentPathOut varchar(255) output, 
	@TemplateNameOut varchar(255) output, 
	@SequenceOut int output, 
	@CreatedDateTimeOut datetime output, 
	@VersionIdOut timestamp output
AS

	declare @ParentSequence varchar(50)
	select @ParentPathOut = isNull(ParentPath,'') + Name + '/', @ParentSequence = isNull(ParentSequence,'')  + cast(Sequence as varchar(3)) From Posts where Id = @ParentId
	
	if exists (select null from Post_View where Id = @Id) begin
		declare @OldName varchar(255)
		declare @OldParentId int
		declare @OldParentPath varchar(255)
		declare @OldSequence int
		select @OldParentId = ParentId, @OldParentPath = ParentPath, @OldName = Name, @OldSequence = Sequence From [Posts] Where Id = @Id
		
		update [Posts]
		set
			SiteId = @SiteId,
			ParentId = @ParentId,
			ParentPath = @ParentPathOut,
			Name = @Name,
			DisplayName = @DisplayName,
			TemplateId = @TemplateId,
			ThumbnailId = @ThumbnailId,
			Summary = @Summary,
			Tags = @Tags,
			Sequence = @Sequence,
			ParentSequence = @ParentSequence
		where
			Id = @Id
			and VersionId = @VersionId
		if @@RowCount <> 1 
			return -100
		else
			set @IdOut = @Id
			
		--Update any old child parent urls
		if @OldName <> @Name or @OldParentId <> @ParentId begin
			update [Posts]
				set ParentPath = Replace(ParentPath, isNull(@OldParentPath, '') + @OldName + '/', isNull(@ParentPathOut, '') + @Name + '/')
			from [Posts] 
			where SiteId = @SiteId 
				and ParentPath like isNull(@OldParentPath, '') + @OldName + '/%'
		end
		if @OldSequence <> @Sequence begin
			Update [Posts]
				set ParentSequence = IsNull(@ParentSequence, '') + Cast(@Sequence as varchar(3)) + SubString(ParentSequence, Len(@ParentSequence) + 1, Len(ParentSequence) - Len(@ParentSequence) - 1)
			from acms.Posts 
			where SiteId = @SiteId
				and ParentPath like isNull(@ParentPathOut, '') + @Name +  '/%'
		end

	end
	else if @Id is null or @Id = 0 begin
		select @Sequence = isNull(Max(Sequence) + 1, 0) from Post_View where ParentId = @ParentId	
		
		insert [Posts]
			(SiteId, ParentId, ParentPath, Name, DisplayName, Sequence, ParentSequence, TemplateId, ThumbnailId, Summary, Tags)
		values
			(@SiteId, @ParentId, @ParentPathOut, @Name, @DisplayName, @Sequence, @ParentSequence, @TemplateId, @ThumbnailId, @Summary, @Tags)
		
		set @IdOut = @@Identity
	end
	else begin
		return -200
	end
	
	select 
		@SiteNameOut = SiteName,
		@TemplateNameOut = TemplateName,
		@CreatedDateTimeOut = CreatedDateTime,
		@SequenceOut = Sequence,
		@VersionIdOut = VersionId
	from Post_View
	where Id = @IdOut
RETURN 0;